<template>
  <div>
    <div ref="chart" :class="className" :style="{height:height,width:width}" />
  </div>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')
import resize from '../../mixins/resize'

export default {
  components: {
  },
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.query()
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    query() {
      const ret = this.chartData
      const seriesData = []
      let legendData = [...new Set(ret.map(item => item.firstCategoryName))]
      legendData.forEach(item => {
        let value = 0
        ret.filter(s => s.firstCategoryName === item).forEach(item => {
          value += item.medicineCount
        })
        seriesData.push({
          value,
          name: item
        })
      })
      legendData = [...legendData].slice(0, 5)
      this.chart.clear()
      this.setOptions({
        seriesData,
        legendData
      })
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chart, 'macarons')
      this.setOptions()
    },
    setOptions({ legendData = [], seriesData } = {}) {
      this.chart.setOption({
        title: {
          text: '药品销售种类',
          bottom: '4',
          left: 'center',
          textStyle: {
            color: '#999'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        grid: {
        },
        legend: {
          top: '0',
          left: 'center',
          data: legendData
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: true,
            label: {
              show: true
            },
            labelLine: {
              show: true
            },
            data: seriesData
          }
        ]
      })
    }
  }
}
</script>
